<template>
  <view class="content">
    <u-form ref="addform" :errorType="errorType" :model="model" :rules="rules">
      <view class="formBox">
        <view class="title">基础信息</view>
        <u-form-item :label-position="labelPosition" label="展示区域" label-width="150" prop="showArea" required>
          <u-radio-group v-model="showAreaName" :width="radioCheckWidth" :wrap="radioCheckWrap">
            <u-radio v-for="(item, index) in showAreaList" :key="index" :name="item.name" shape="circle"
                     @change="radioChange(item.name, 'showArea', item.value)">
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item v-if="model.showArea == 1" :label-position="labelPosition" :required="model.showArea == 1"
                     label="商品类型" label-width="150" prop="goodsType">
          <u-radio-group v-model="goodsTypeName" :width="radioCheckWidth" :wrap="radioCheckWrap">
            <u-radio v-for="(item, index) in goodsTypeList" :key="index" :name="item.name" shape="circle"
                     @change="radioChange(item.name, 'goodsType', item.value)">
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item v-if="model.showArea == 2" :label-position="labelPosition" :required="model.showArea == 2"
                     label="服务类型" label-width="150" prop="serverType">
          <u-radio-group v-model="serverTypeName" :width="radioCheckWidth" :wrap="radioCheckWrap">
            <u-radio v-for="(item, index) in serverTypeList" :key="index" :name="item.name" shape="circle"
                     @change="radioChange(item.name, 'serverType', item.value)">
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item v-if="model.showArea == 2" :label-position="labelPosition" :required="model.showArea == 2"
                     label="服务标签" label-width="150" prop="serverLabel">
          <u-input
              v-model="model.serverLabel"
              :select-open="selectShow"
              input-align="right"
              placeholder="请选择服务标签"
              type="select"
              @click="selectShow = true"
          ></u-input>
        </u-form-item>
        <u-form-item :label-position="labelPosition" label="商品名称" label-width="150" prop="goodsServerName" required>
          <u-input v-model="model.goodsServerName" input-align="right" placeholder="请输入商品名称" type="text"></u-input>
        </u-form-item>
        <u-form-item :label-position="labelPosition" label="上传图片" label-width="200" prop="goodsUrl" required>
          <u-upload
              :action="action"
              :auto-upload="true"
              :max-count="model.showArea == 2 ? 1 : 6"
              :max-size="5 * 1024 * 1024"
              :show-progress="false"
              :upload-text="model.showArea == 2 ? '上传图片(最多上传1张)' : '上传图片(最多上传6张)'"
              height="160"
              name="files"
              width="160"
              @on-success="onSuccess"
              @on-list-change="onListChange"
          ></u-upload>
        </u-form-item>
        <u-form-item v-if="model.showArea == 2" :label-position="labelPosition" :required="model.showArea == 2"
                     label="套餐介绍" label-width="150" prop="explain">
          <u-input v-model="model.explain" input-align="right" placeholder="请输入介绍" type="text"></u-input>
        </u-form-item>
        <u-form-item v-if="model.showArea == 2" :label-position="labelPosition" label="购买须知" label-width="150"
                     prop="notice">
          <u-input v-model="model.notice" input-align="right" placeholder="请输入介绍" type="text"></u-input>
        </u-form-item>
      </view>
      <view v-if="model.showArea == 1 && model.goodsType != 59" class="formBox">
        <view class="title">商品/服务项目</view>
        <view class="f-c-sb" style="line-height: 100rpx;">
          <view class="value">
            <span style="    color: #fa3534;">*</span>
            商品/服务项目
          </view>
          <view class="f-c-fs" style="color: #2979ff;" @click="addShop(1, 0)">
            <u-icon color="#2979ff" name="plus-circle-fill" size="35" style="margin-right: 8rpx;"></u-icon>
            新增
          </view>
        </view>
        <view v-for="(item, index) in shopList" :key="index" class="list">
          <view class="f-c-sb name-wrapper">
            <view class="name">{{ item.name }}</view>
            <view class="f-c-fs">
              <u-icon color="#999999" name="edit-pen-fill" size="40" style="margin-right: 15rpx;"
                      @click="addShop(2, index)"></u-icon>
              <u-icon color="#999999" name="trash-fill" size="40" @click="deletShop(index)"></u-icon>
            </view>
          </view>
          <view class="info">
            <view class="f-c-fs num">
              <view class="label">
                原价：
                <text class="value">￥{{ item.oldPrice }}</text>
              </view>
              <view class="label">
                数量：
                <text class="value">{{ item.number }}</text>
              </view>
            </view>
            <view>
              <view class="">描述（20字符）</view>
              <view>{{ item.content }}</view>
            </view>
          </view>
        </view>
      </view>
      <view class="formBox">
        <view class="title">购买信息</view>
        <u-form-item v-if="model.showArea == 1" :label-position="labelPosition" label="支付方式" label-width="150"
                     prop="buyWay" required>
          <u-radio-group v-model="buyWayName" :width="radioCheckWidth" :wrap="radioCheckWrap">
            <u-radio v-for="(item, index) in buyWayList" :key="index" :name="item.name" shape="circle"
                     @change="radioChange(item.name, 'buyWay', item.value)">
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item v-if="model.showArea == 2" :label-position="labelPosition" label="支付方式" label-width="150"
                     prop="buyWay" required>
          <u-radio-group v-model="buyWayName" :width="radioCheckWidth" :wrap="radioCheckWrap">
            <u-radio v-for="(item, index) in buyWayList1" :key="index" :name="item.name" shape="circle"
                     @change="radioChange(item.name, 'buyWay', item.value)">
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item :label-position="labelPosition" label="原价(元)" label-width="150" prop="costPrice" required>
          <u-input v-model="model.costPrice" :disabled="model.showArea == 1 && model.goodsType != 59"
                   input-align="right" placeholder="请输入原价" type="digit"></u-input>
        </u-form-item>
        <u-form-item v-if="model.buyWay == 2" :label-position="labelPosition" label="积分" label-width="150"
                     prop="nowPrice" required>
          <u-input v-model="model.nowPrice" input-align="right" placeholder="请输入积分" type="digit"></u-input>
        </u-form-item>
        <u-form-item v-else :label-position="labelPosition" label="现价(元)" label-width="150" prop="nowPrice" required>
          <u-input v-model="model.nowPrice" input-align="right" placeholder="请输入现价" type="digit"></u-input>
        </u-form-item>
        <u-form-item v-if="false" :label-position="labelPosition" label="剩余数量" label-width="150" prop="surplusNumber">
          <u-input v-model="model.surplusNumber" input-align="right" placeholder="请输入剩余数量" type="digit"></u-input>
        </u-form-item>
        <u-form-item :label-position="labelPosition" label="虚拟购买人数" label-width="200" prop="inventedNumber">
          <u-input v-model="model.inventedNumber" input-align="right" placeholder="请输入虚拟购买人数" type="digit"></u-input>
        </u-form-item>
        <u-form-item :label-position="labelPosition" label="库存" label-width="150" prop="stockNumber" required>
          <u-input v-model="model.stockNumber" input-align="right" placeholder="请输入库存" type="digit"></u-input>
        </u-form-item>
        <u-form-item :label-position="labelPosition" label="支付退款" label-width="150" prop="isRefund" required>
          <u-radio-group v-model="isRefundName" :width="radioCheckWidth" :wrap="radioCheckWrap">
            <u-radio v-for="(item, index) in isRefundList" :key="index" :name="item.name" shape="circle"
                     @change="radioChange(item.name, 'isRefund', item.value)">
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item v-if="model.showArea == 1" :label-position="labelPosition" label="使用方式" label-width="150"
                     prop="useWay" required>
          <u-radio-group v-model="useWayNmae" :width="radioCheckWidth" :wrap="radioCheckWrap">
            <u-radio v-for="(item, index) in useWayList" :key="index" :name="item.name" shape="circle"
                     @change="radioChange(item.name, 'useWay', item.value)">
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item :label-position="labelPosition" label="使用门店" label-width="150" prop="useStores" required>
          <u-radio-group v-model="useStoresName" :width="radioCheckWidth" :wrap="radioCheckWrap">
            <u-radio v-for="(item, index) in useStoresList" :key="index" :name="item.name" shape="circle"
                     @change="radioChange(item.name, 'useStores', item.value)">
              {{ item.name }}
            </u-radio>
          </u-radio-group>
        </u-form-item>
        <u-form-item v-if="useStoresName == '选择门店'" :label-position="labelPosition" label="选择门店" label-width="150"
                     prop="useStores" required>
          <view v-if="model.useStores.split(',').length && model.useStores.length != 0 && selectStore.length == 0"
                style="width: 100%;" @click="goselectStore">
            已选择{{ model.useStores.split(',').length }}家门店
          </view>
          <view v-else-if="selectStore.length != 0" style="width: 100%;" @click="goselectStore">已选择{{
              selectStore.length
            }}家门店
          </view>
          <view v-else style="width: 100%;" @click="goselectStore">请选择门店</view>
        </u-form-item>
      </view>
      <view class="formBox">
        <view class="title">商品详情介绍</view>
        <u-form-item :label-position="labelPosition" label="商品详情" label-width="150" prop="details" required>
          <view style="width: 100%;" @click="goShopDetail">{{ model.details.length > 0 ? '修改活动内容' : '请输入商品详情' }}</view>
          <!-- <u-input input-align="right"  placeholder="请输入商品详情" disabled v-model="model.details" @click="goShopDetail" type="text"></u-input> -->
        </u-form-item>
      </view>
    </u-form>
    <u-popup v-model="show" border-radius="22" closeable mode="bottom" safe-area-inset-bottom>
      <view class="formBox-wrapper">
        <view class="formBox">
          <u-form ref="uShop" :model="shop">
            <u-form-item label="商品服务名称" label-width="200rpx" prop="name" required>
              <u-input v-model="shop.name" input-align="right"/>
            </u-form-item>
            <u-form-item label="销售价" label-width="200rpx" prop="oldPrice" required>
              <u-input v-model="shop.oldPrice" input-align="right" type="digit"/>
            </u-form-item>
            <u-form-item label="数量" label-width="200rpx" prop="number" required>
              <u-input v-model="shop.number" input-align="right" type="digit"/>
            </u-form-item>
            <u-form-item label="备注" label-position="top" label-width="200rpx" prop="content">
              <u-input v-model="shop.content" input-align="right" maxlength="20" type="textarea "/>
            </u-form-item>
          </u-form>
        </view>

        <view class="lxdBtn" @click="save">保存</view>
      </view>
    </u-popup>
    <u-select v-model="selectShow" :list="serverLabelList" label-name="value" mode="single-column" value-name="dictId"
              @confirm="selectConfirm"></u-select>
    <view class="lxdBtn" @click="submit">提交</view>
  </view>
</template>

<script>
import {goodsserverSave, serverLabelListFn} from '@/api/index.js';
import {mapGetters} from 'vuex';

export default {
  data() {
    return {
      show: false,
      selectShow: false,
      model: {
        showArea: '1',
        goodsType: '60',
        serverType: '1',
        goodsServerName: '',
        goodsUrl: '',
        buyWay: '1',
        notice: '',
        explain: '',
        costPrice: '',
        nowPrice: '',
        surplusNumber: '',
        inventedNumber: '',
        stockNumber: '',
        isRefund: '1',
        useWay: '1',
        useStores: '',
        details: '',
        serverLabelId: '',
        serverLabel: ''
      },
      rules: {
        goodsType: [
          {
            validator: (rule, value, callback) => {
              // 调用uView自带的js验证规则，详见：https://www.uviewui.com/js/test.html
              console.log(123);
              if (this.showAreaName === '商城' && this.goodsTypeName === '') {
                callback(new Error('请选择商品类型'));
              } else {
                callback();
              }
            },
            message: '请选择商品类型',
            // 触发器可以同时用blur和change，二者之间用英文逗号隔开
            trigger: ['change', 'blur']
          }
        ],
        goodsServerName: [
          {
            required: true,
            message: '此为必填字段',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        goodsUrl: [
          {
            required: true,
            message: '请上传图片',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        explain: [
          {
            required: true,
            message: '此为必填字段',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        costPrice: [
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              return this.$u.test.amount(value);
            },
            message: '金额格式不正确',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur']
          }
        ],
        nowPrice: [
          {
            required: true,
            message: '此为必填字段',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          },
          {
            // 自定义验证函数，见上说明
            validator: (rule, value, callback) => {
              return this.$u.test.amount(value);
            },
            message: '金额格式不正确',
            // 触发器可以同时用blur和change
            trigger: ['change', 'blur']
          }
        ],
        stockNumber: [
          {
            required: true,
            message: '此为必填字段',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        serverLabelId: '',
        serverLabel: ''
      },
      showAreaList: [
        {
          name: '商城',
          value: 1,
          checked: false
        },
        {
          name: '门店服务',
          value: 2,
          checked: false
        }
      ],
      serverLabelList: [
        {
          label: '标准洗车',
          value: '1'
        },
        {
          label: '全车精洗',
          value: '2'
        }
      ],
      isRefundList: [
        {
          name: '不支持',
          value: 1,
          checked: false
        },
        {
          name: '支持',
          value: 2,
          checked: false
        }
      ],

      useWayList: [
        {
          name: '邮寄',
          value: 1,
          checked: false
        },
        {
          name: '到店核销',
          value: 2,
          checked: false
        },
        {
          name: '自提',
          value: 3,
          checked: false
        }
      ],
      buyWayName: '货币购买',
      buyWayList: [
        {
          name: '货币购买',
          value: 1,
          checked: false
        },
        {
          name: '积分兑换',
          value: 2,
          checked: false
        }
      ], buyWayList1: [
        {
          name: '货币购买',
          value: 1,
          checked: false
        }
      ],
      useStoresName: '当前门店',
      useStoresList: [
        {
          name: '当前门店',
          value: 1,
          checked: false
        },
        {
          name: '选择门店',
          value: 2,
          checked: false
        }
      ],
      goodsTypeList: [
        {
          name: '套餐',
          value: 60,
          checked: false
        },
        {
          name: '卡券',
          value: 61,
          checked: false
        },
        {
          name: '商品',
          value: 59,
          checked: false
        }
      ],
      serverTypeList: [
        {
          name: '洗车',
          value: 1,
          checked: false
        },
        {
          name: '钣喷',
          value: 2,
          checked: false
        },
        {
          name: '保养',
          value: 3,
          checked: false
        }
      ],
      labelPosition: 'left',
      radioCheckWidth: 'auto',
      radioCheckWrap: false,
      errorType: ['message'],
      showAreaName: '商城',
      serverTypeName: '洗车',
      goodsTypeName: '套餐',
      buyWayName: '货币购买',
      isRefundName: '不支持',
      useWayNmae: '邮寄',
      fileList: [
        {
          url: ''
        }
      ],
      action: 'https://sj.shopec.com.cn/hty-manage-api/upload/files',
      editStatus: 1, //1、新增 2、编辑
      editStatusIndex: 0, //1、新增 2、编辑
      shopList: [],
      shop: {
        name: '',
        oldPrice: '',
        number: '',
        content: ''
      },
      rulesShop: {
        name: [
          {
            validator: (rule, value, callback) => {
              if (!value.length) {
                return false;
              } else {
                callback();
              }
            },
            message: '请输入',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        oldPrice: [
          {
            validator: (rule, value, callback) => {
              if (!String(value).length) {
                return false;
              } else {
                callback();
              }
            },
            message: '请输入',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ],
        number: [
          {
            validator: (rule, value, callback) => {
              if (!String(value).length) {
                return false;
              } else {
                callback();
              }
            },
            message: '请输入',
            // 可以单个或者同时写两个触发验证方式
            trigger: ['change', 'blur']
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'selectStore'])
  },
  onReady() {
    this.$refs.addform.setRules(this.rules);
    this.$refs.uShop.setRules(this.rulesShop);
    this.getserverLabelList();
  },
  onShow() {
    this.model.details = this.$get('addHtml') ? this.$get('addHtml') : '';
  },
  onUnload() {
    this.$remove('addHtml');
    this.$remove('selectStoreIds');
  },
  methods: {
    addShop(type, index) {
      this.show = true;
      this.editStatus = type;
      this.editStatusIndex = index;
      if (type == 2) {
        this.shop = this.shopList[index];
        this.$forceUpdate();
      } else {
        this.shop = {
          name: '',
          oldPrice: '',
          number: '',
          content: ''
        };
      }
    },
    deletShop(index) {
      this.shopList.splice(index, 1);
      var num = 0;
      this.shopList.forEach((val, index) => {
        num += val.oldPrice * val.number;
      });
      this.model.costPrice = num;
    },
    selectConfirm(e) {
      console.log(e);
      this.model.serverLabel = '';
      e.map((val, index) => {
        this.model.serverLabel = val.label;
        this.model.serverLabelId = val.value;
      });
    },
    save() {
      this.$refs.uShop.validate(valid => {
        if (valid) {
          console.log('验证通过');
          if (this.editStatus == 1) {
            this.shopList.push(JSON.parse(JSON.stringify(this.shop)));
          } else if (this.editStatus == 2) {
            this.shopList[this.editStatusIndex] = JSON.parse(JSON.stringify(this.shop));
          }
          var num = 0;
          this.shopList.forEach((val, index) => {
            num += val.oldPrice * val.number;
          });
          this.model.costPrice = num;
          this.show = false;
        } else {
          console.log('验证失败');
        }
      });
    },
    radioChange(name, type, value) {
      this[type + 'name'] = name;
      this.model[type] = value;
      if (type == 'serverType') {
        this.getserverLabelList();
      }
      if (type == 'showArea') {
        if (value == 2) {
          this.buyWayName = '货币购买'
          this.model.buyWay = '1'
        }
      }
      if (type == 'goodsType' && value != 59) {
        var num = 0;
        this.shopList.forEach((val, index) => {
          num += val.oldPrice * val.number;
        });
        this.model.costPrice = num;
      } else if (type == 'goodsType' && value == 59) {
        this.model.costPrice = 0;
      }
      if (name == '选择门店') {
        this.goselectStore();
      } else if (name == '当前门店') {
        this.model.useStores = this.userInfo.storeBasicId;
      }
    },
    goselectStore() {
      // this.$store.commit('setSelectStoreStr',this.model.useStores);
      this.$navigateTo('/pages/selectStore/selectStore', {});
    },
    onListChange(lists, index) {
      this.fileList = lists;
    },
    goShopDetail() {
      this.$put('addHtml', this.model.details);
      this.$navigateTo('../shopDetail/shopDetail', {});
    },
    getserverLabelList() {
      serverLabelListFn({serverType: this.model.serverType}).then(res => {
        var isCheckStatus = false;
        res.data.forEach((val, index) => {
          if (val.value == this.model.serverLabel && val.dictId == this.model.serverLabelId) {
            isCheckStatus = true;
          }
        });
        if (!isCheckStatus) {
          this.model.serverLabel = '';
          this.model.serverLabelId = '';
        }
        this.serverLabelList = res.data;
      });
    },
    onSuccess(data, index, lists, name) {
      console.log(data, index, lists, name);
      var str = '';
      lists.forEach((val, index) => {
        if (index == lists.length - 1) {
          str = str + val.response.data.saveUrl;
        } else {
          str = str + val.response.data.saveUrl + ',';
        }
      });
      this.model.goodsUrl = str;
    },
    submit() {
      this.$refs.addform.validate(valid => {
        if (valid) {
          console.log('验证通过');
          var data = {
            buyWay: 0,
            costPrice: 0,
            details: '',
            explain: '',
            goodsServerName: '',
            goodsType: 0,
            goodsUrl: '',
            gsId: '',
            inventedNumber: 0,
            isRefund: 0,
            notice: '',
            nowPrice: 0,
            serverLabel: '',
            serverLabelId: '',
            serverType: 0,
            showArea: 0,
            stockNumber: 0,
            surplusNumber: 0,
            useStores: this.userInfo.storeBasicId,
            useWay: 0
          };
          if (this.useStoresName == '选择门店') {
            this.model.useStores = '';
            var str = '';
            if (this.selectStore) {
              this.selectStore.forEach((val, index) => {
                if (index == this.selectStore.length - 1) {
                  str = str + val.storeId;
                } else {
                  str = str + val.storeId + ',';
                }
              });
              this.model.useStores = str;
            } else {
              uni.showToast({
                title: '请选择使用门店',
                icon: 'none'
              });
            }
          } else if (this.useStoresName == '当前门店') {
            this.model.useStores = this.userInfo.storeBasicId;
          }
          for (let key in data) {
            data[key] = this.model[key];
          }
          if (data.showArea == 1) {
            delete data.serverType;
            delete data.serverLabel;
            delete data.serverLabelId;
          } else {
            delete data.goodsType;
          }
          data.storeBasicId = this.userInfo.storeBasicId;
          data.details = encodeURI(this.model.details);
          if (data.details.length == 0) {
            uni.showToast({
              title: '请填写商品详情',
              icon: 'none'
            });
            return;
          }
          if (data.showArea == 1 && data.goodsType != 59) {
            if (this.shopList.length > 0) {
              data.gsDtos = this.shopList;
            } else {
              uni.showToast({
                title: '请添加商品/服务项目',
                icon: 'none'
              });
              return;
            }
          } else {
            delete data.gsDtos;
          }
          goodsserverSave(data).then(res => {
            if (res.code == 1) {
              this.$store.commit('setSelectStore', []);
              this.$put('goodsserverSave', 'update')
              uni.navigateBack({
                delta: 1
              });
            } else {
              uni.showToast({
                title: res.msg,
                icon: 'none'
              });
            }
          });
        } else {
          console.log('验证失败');
        }
      });
    }
  }
};
</script>

<style lang="less">
.content {
  width: 100%;
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx 0;
  box-sizing: border-box;
}
.formBox-wrapper {
	height: 70vh;
	padding-top: 50rpx;
}
.list:nth-last-child(1) {
	border: 0;
}
.list {
	border-bottom: 1px solid #ccc;
	width: 100%;
	padding-bottom: 40rpx;

	.name {
		font-size: 28rpx;
		font-weight: 700;
		text-align: left;
		color: #131313;
		line-height: 36px;
	}
	.info {
		line-height: 50rpx;
		.label {
			width: 50%;
			line-height: 80rpx;
		}
	}
}
</style>
